﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcJqGrid;
using PagedList;
using WebApp.Commons;
using WebApp.Data;
using WebApp.Models;
using WebApp.Services;

namespace WebApp.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        private EmployeeService _service;
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetUsers(GridSettings gridSettings,string keyword)
        {
            _service = new EmployeeService();

            if (string.IsNullOrEmpty(keyword))
                keyword = string.Empty;
            var realCount = 0;
            var datas = _service.GetEmployees(gridSettings.PageIndex,
                                          gridSettings.PageSize,
                                          gridSettings.SortColumn,
                                          gridSettings.SortOrder, 
                                          keyword, 
                                          ref realCount);
            //var datas = _service.GetEmployees(ref realCount);

            var lists = new List<EmployeeModel>();
            foreach (var model in datas)
            {
                var item = new EmployeeModel();
                item.UserId = model.user_id;
                item.UserTypeId = model.user_type_id;
                item.UserFirstName = model.user_firstname;
                item.UserLastName = model.user_lastname;
                item.UserFullName = model.user_firstname + " " + model.user_lastname;
                item.UserIdNo = model.user_id_no;
                item.UserTelNo = model.user_tel_no;
                item.UserStatus = model.user_status;
                item.UserLoginName = model.user_login_name;
                item.UserPassword = model.user_password;
                item.UserCreateBy = "";
                item.UserCreateDate = model.user_create_date.HasValue ? model.user_create_date.Value : DateTime.Now;
                item.UserUpdateDate = model.user_update_date.HasValue ? model.user_update_date.Value : DateTime.Now;

                lists.Add(item);
            }

            var totalBUs = realCount;
            var totalPage = totalBUs / gridSettings.PageSize;

            if (totalPage > Convert.ToInt32(totalPage))
            {
                totalPage = totalPage + 1;
            }

            var jsonData = new
            {
                total = Convert.ToInt32(totalPage),
                page = gridSettings.PageIndex,
                records = totalBUs,
                rows = (
                            from e in lists
                            select new
                            {
                                id = e.UserId,
                                cell = new[] {
                                            e.UserId.ToString(),
                                            e.UserTypeId.ToString(),
                                            e.UserFirstName,
                                            e.UserLastName,
                                            e.UserIdNo,
                                            e.UserTelNo,
                                            e.UserStatus,
                                            e.UserLoginName,
                                            e.UserPassword,
                                            e.UserCreateDate.ToLongDateString()
                                            }
                            }
                        ).ToPagedList(1, gridSettings.PageSize).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public string GetEmpListHtml()
        {
            _service = new EmployeeService();
            var sTag = _service.GetEmployeeTypes().Aggregate("<select>", (current, emp) => current + "<option value='" + emp.user_type_id + "'>" + emp.user_type_name + "</option>");

            return sTag + "</select>";
        }

        public JsonResult GetEmployeeTypeList()
        {
            _service = new EmployeeService();
            var empList = _service.GetEmployeeTypes();
            foreach (var item in empList)
            {
                
            }
            var jsonData = new{
                count = empList.Count,
                rows = (from e in empList
                            select new
                            {
                                id = e.user_type_id,
                                cell = new[]{
                                          e.user_type_code.ToString(),
                                          e.user_type_name
                                }
                            })
                                   
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Update(tbl_user emp, FormCollection formCollection)
        {
            _service = new EmployeeService();

            var isPass = false;
            var iMessage = string.Empty;
            //formCollection
            var operation = formCollection["oper"];

            if (operation.Equals("add") || operation.Equals("edit"))
            {
                _service.UpdateEmployee(emp);
            }
            else if (operation.Equals("del"))
            {
                _service.DeleteEmployee(emp);
            }

            return Json(new { isPass, iMessage });
        }

        public JsonResult ChangePassword(tbl_user emp)
        {
            var isPass = false;
            var iMessage = string.Empty;
            _service = new EmployeeService();
            if(string.IsNullOrEmpty(emp.user_password) || emp.user_id == 0)
            {
                iMessage = "user_id or user_password missing";
                return Json(new { isPass, iMessage});
            }
            _service.ChangePassword(emp);
            isPass = true;
            return Json(new { isPass, iMessage });
        }
    }
}
